local MINOR_VERSION = tonumber(("$Revision: 1 $"):match("%d+"))
if MINOR_VERSION > EQdkpRT.MINOR_VERSION then EQdkpRT.MINOR_VERSION = MINOR_VERSION end

local gui = LibStub("AceGUI-3.0")
local L = LibStub("AceLocale-3.0"):GetLocale("EQdkpRT")
local module_icons = {}
-- geh local Threat = LibStub("Threat-2.0")
local math_abs = math.abs
local Media = LibStub("LibSharedMedia-3.0")

local table_sort = _G.table.sort

function EQdkpRT:CreateFrame()
	self.Anchor = CreateFrame("Frame", "EQdkpRTAnchor", UIParent)
	self.Anchor:SetResizable(true)
	self.Anchor:SetMinResize(168, 150)
	self.Anchor:SetMovable(true)
	self.Anchor:SetPoint("CENTER", UIParent, "CENTER")
	self.Anchor:SetWidth(225)
	self.Anchor:SetHeight(150)
	self.Anchor:SetScript("OnSizeChanged", function()
		EQdkpRT:ResizeBars()
		if EQdkpRT.activeModule then EQdkpRT.activeModule:UpdateLayout() end
	end)

	------------------------------------------------------------------
	-- Title
	------------------------------------------------------------------
	self.Title = CreateFrame("Frame", "EQdkpRTTitle", self.Anchor)
	self.Title:SetPoint("TOPLEFT", self.Anchor, "TOPLEFT")
	self.Title:SetPoint("TOPRIGHT", self.Anchor, "TOPRIGHT")
	self.Title:SetHeight(self.Options["Skin.Title.Height"])
	self.Title:EnableMouse(true)

	self.TitleText = self.Title:CreateFontString(nil, nil, "GameFontNormal")
	self.TitleText:SetPoint("LEFT", self.Title, "LEFT", 10, 0)
	self.defaultTitle = "EQdkpRT|cffffcc002|r"
	self:SetTitle()
	-- self:ScheduleRepeatingTimer("SetTitleInternal", 10)
	self.TitleText:SetJustifyH("LEFT")
	self.TitleText:SetTextColor(1,1,1,0.95)

	self.VersionText = self.Title:CreateFontString(nil, nil, "GameFontNormal")
	self.VersionText:SetPoint("TOPRIGHT", self.Title, "TOPRIGHT", -6, -4)
  self.VersionText:SetText(("r|cffffffff%s|r"):format(self.version))
	local f, s, p = self.VersionText:GetFont()
	self.VersionText:SetFont(f, 8, p)

	self.OutOfDateText = self.Title:CreateFontString(nil, nil, "GameFontNormal")
	self.OutOfDateText:SetPoint("TOPRIGHT", self.VersionText, "BOTTOMRIGHT", 0, 0)
	self.OutOfDateText:SetText("")

	local f, s, p = self.VersionText:GetFont()
	self.OutOfDateText:SetFont(f, 8, p)

	self.TitleText:SetPoint("RIGHT", self.VersionText, "LEFT", -5, 0)

	self.Title:SetScript("OnMouseDown", function() if not EQdkpRT.Options["Lock"] then EQdkpRT.Anchor:StartMoving(); end end)
	self.Title:SetScript("OnMouseUp", function()
		EQdkpRT.Anchor:StopMovingOrSizing();
		EQdkpRT:SetAnchors()
	end)
	EQdkpRT:InjectFrameOptions("Title", EQdkpRT.configOptions.args.display.args.title)

	------------------------------------------------------------------
	-- Module Buttons
	------------------------------------------------------------------
	self.ModuleList = CreateFrame("Frame", "EQdkpRTModuleButtons", self.Anchor)
	self.ModuleList:SetHeight(self.Options["Skin.Modules.Height"])
	self.ModuleList:SetPoint("BOTTOMLEFT", self.Anchor, "BOTTOMLEFT")
	self.ModuleList:SetPoint("BOTTOMRIGHT", self.Anchor, "BOTTOMRIGHT")
	local configButton = CreateFrame("Button", nil, self.ModuleList)
	configButton:SetNormalTexture("Interface\\Icons\\INV_Misc_Wrench_01")
	configButton:SetHighlightTexture("Interface\\Buttons\\ButtonHilight-Square")
	configButton:SetScript("OnClick", EQdkpRT.ShowConfig)
	configButton:SetPoint("RIGHT", self.ModuleList, "RIGHT", -7, 0)
	configButton:SetScript("OnEnter", function(self)
		GameTooltip:SetOwner(self, "ANCHOR_RIGHT");
		GameTooltip:AddLine(L["Configure Omen"])
		GameTooltip:Show()
	end)
	configButton:SetScript("OnLeave", function(self) GameTooltip:Hide() end)

	configButton:SetWidth(self.ModuleList:GetHeight() - 12)
	configButton:SetHeight(self.ModuleList:GetHeight() - 12)

	self.ModuleList.Config = configButton

	EQdkpRT:InjectFrameOptions("ModuleList", EQdkpRT.configOptions.args.display.args.moduleList)

	------------------------------------------------------------------
	-- BarList
	------------------------------------------------------------------
--	self.BarList = CreateFrame("Frame", "EQdkpRTBarList", self.Anchor,"FauxScrollFrameTemplate")
	self.BarList = CreateFrame("Frame", "EQdkpRTBarList", self.Anchor)
	self.BarList:SetFrameStrata("MEDIUM")
	self.BarList:SetResizable(true)
	self.BarList:EnableMouse(true)
	self.BarList:SetPoint("TOPLEFT", self.Title, "BOTTOMLEFT")
	self.BarList:SetPoint("TOPRIGHT", self.Title, "BOTTOMRIGHT")
	self.BarList:SetPoint("BOTTOMLEFT", self.ModuleList, "TOPLEFT")
	self.BarList:SetPoint("BOTTOMRIGHT", self.ModuleList, "TOPRIGHT")
	self.BarList:SetScript("OnMouseDown", function() if not EQdkpRT.Options["Lock"] then EQdkpRT.Anchor:StartMoving(); end end)
	self.BarList:SetScript("OnMouseUp", function()
		EQdkpRT.Anchor:StopMovingOrSizing();
		EQdkpRT:SetAnchors()
	end)

	EQdkpRT:InjectFrameOptions("BarList", EQdkpRT.configOptions.args.display.args.barList)
	EQdkpRT:InjectFrameOptions("Frames", EQdkpRT.configOptions.args.display.args.defaults)

-- geh column test

	local col1 = CreateFrame("Button", nil, self.BarList)
	col1.obj = self
	col1.id = id
	col1:SetWidth(64)
	col1:SetHeight(24)

	col1:SetPoint("TOPLEFT", self.BarList, "TOPLEFT")
	col1:SetPoint("TOPRIGHT", self.BarList, "TOP")

 	col1:SetHighlightTexture("Interface\\PaperDollInfoFrame\\UI-Character-Tab-Highlight")
	col1:GetHighlightTexture():SetBlendMode("ADD")
	col1:GetHighlightTexture():SetPoint("TOPLEFT",col1,"TOPLEFT")
	col1:GetHighlightTexture():SetPoint("BOTTOMRIGHT",col1,"BOTTOMRIGHT")

	local left = col1:CreateTexture(nil,"BACKGROUND")
	local middle = col1:CreateTexture(nil,"BACKGROUND")
	local right = col1:CreateTexture(nil,"BACKGROUND")
	local text = col1:CreateFontString(nil,"BACKGROUND","GameFontNormalSmall")
		
	col1.text = text
	col1.left = left
	col1.right = right
	col1.middle = middle
	col1.SetText = Tab_SetText
	col1.SetSelected = Tab_SetSelected
	col1.SetDisabled = Tab_SetDisabled
		
	text:SetHeight(18)
		
	left:SetWidth(16)
	left:SetHeight(32)
	middle:SetWidth(44)
	middle:SetHeight(32)
	right:SetWidth(16)
	right:SetHeight(32)
		
	left:SetTexCoord(0,0.25,0,1)
	middle:SetTexCoord(0.25,0.75,0,1)
	right:SetTexCoord(0.75,1,0,1)
		
	left:SetPoint("TOPLEFT",col1,"TOPLEFT",0,0)
	right:SetPoint("TOPRIGHT",col1,"TOPRIGHT",0,0)
		
	middle:SetPoint("LEFT",left,"RIGHT",0,0)
	middle:SetPoint("RIGHT",right,"LEFT",0,0)
		
	col1:SetText("Column 1")
	local f, s, p = self.VersionText:GetFont()
	col1:SetFont(f, 10, p)

	col1:SetScript("OnClick", function(self)
		col1:SetText("CLICKED")
	end)

-- Data Col1
	dataCol1 = CreateFrame("Frame", "DataCol1", self.BarList,"FauxScrollFrameTemplate")
	dataCol1:SetFrameStrata("MEDIUM")
	dataCol1:SetResizable(true)
	dataCol1:EnableMouse(true)
	dataCol1:SetPoint("TOPLEFT", col1, "BOTTOMLEFT")
	dataCol1:SetPoint("TOPRIGHT", col1, "BOTTOMRIGHT")

	self.DataCol1 = dataCol1

	EQdkpRT:InjectFrameOptions("DataCol1", EQdkpRT.configOptions.args.display.args.defaults)


	dataCol1.SetText = Tab_SetText
	local text = dataCol1:CreateFontString(nil,"BACKGROUND","GameFontNormalSmall")
	dataCol1.text = text
	dataCol1:SetText("Firstplayer")
	local f, s, p = self.VersionText:GetFont()
	dataCol1:SetFont(f, 10, p)

-- COL 2
	local col2 = CreateFrame("Button",nil,self.BarList)
	col2.obj = self
	col2.id = id	
	col2:SetWidth(64)
	col2:SetHeight(24)
		
	col2:SetPoint("TOPLEFT", col1, "TOPRIGHT")
	col2:SetPoint("TOPRIGHT", self.BarList, "TOPRIGHT")

 	col2:SetHighlightTexture("Interface\\PaperDollInfoFrame\\UI-Character-Tab-Highlight")
	col2:GetHighlightTexture():SetBlendMode("ADD")
	col2:GetHighlightTexture():SetPoint("TOPLEFT",col2,"TOPLEFT")
	col2:GetHighlightTexture():SetPoint("BOTTOMRIGHT",col2,"BOTTOMRIGHT")

	local left = col2:CreateTexture(nil,"BACKGROUND")
	local middle = col2:CreateTexture(nil,"BACKGROUND")
	local right = col2:CreateTexture(nil,"BACKGROUND")
	local text = col2:CreateFontString(nil,"BACKGROUND","GameFontNormalSmall")
		
	col2.text = text
	col2.left = left
	col2.right = right
	col2.middle = middle
	col2.SetText = Tab_SetText
	col2.SetSelected = Tab_SetSelected
	col2.SetDisabled = Tab_SetDisabled
		
	text:SetHeight(18)

	left:SetWidth(16)
	left:SetHeight(32)
	middle:SetWidth(44)
	middle:SetHeight(32)
	right:SetWidth(16)
	right:SetHeight(32)
		
	left:SetTexCoord(0,0.25,0,1)
	middle:SetTexCoord(0.25,0.75,0,1)
	right:SetTexCoord(0.75,1,0,1)
		
	left:SetPoint("TOPLEFT",col2,"TOPLEFT",0,0)
	right:SetPoint("TOPRIGHT",col2,"TOPRIGHT",0,0)
		
	middle:SetPoint("LEFT",left,"RIGHT",0,0)
	middle:SetPoint("RIGHT",right,"LEFT",0,0)
		
	col2:SetText("Column 2")
	local f, s, p = self.VersionText:GetFont()
	col2:SetFont(f, 10, p)
		
-- gehTEST

	------------------------------------------------------------------
	-- Grip
	------------------------------------------------------------------
	local grip = CreateFrame("Button", "EQdkpRTResizeGrip", self.BarList)
	grip:SetNormalTexture("Interface\\AddOns\\EQdkpRT\\Textures\\ResizeGrip")
	grip:SetHighlightTexture("Interface\\AddOns\\EQdkpRT\\Textures\\ResizeGrip")
	grip:SetWidth(16)
	grip:SetHeight(16)
	grip:SetScript("OnMouseDown", function()
		if not EQdkpRT.db.profile.Locked then
			this:GetParent():GetParent():StartSizing()
		end
	end)
	grip:SetScript("OnMouseUp", function()
		this:GetParent():GetParent():StopMovingOrSizing()
	end)
	grip:SetPoint("BOTTOMRIGHT", self.BarList, "BOTTOMRIGHT", 0, 1)
	self.Grip = grip
	self:UpdateVisible()
	self:UpdateDisplay()

end

function EQdkpRT:SetAnchors(useDB)
	local t = EQdkpRT.Options["Skin.Bars.GrowUp"]
	local x, y
	if useDB then
		x, y = self.db.profile.PositionX, self.db.profile.PositionY
		if not x and not y then
			EQdkpRT.Anchor:ClearAllPoints()
			EQdkpRT.Anchor:SetPoint("CENTER", UIParent, "CENTER", 0, 0)
			return
		end
	elseif t then
		x, y = self.Anchor:GetLeft(), self.Anchor:GetBottom()
	else
		x, y = self.Anchor:GetLeft(), self.Anchor:GetTop()
	end
	EQdkpRT.Anchor:ClearAllPoints()
	if t then
		EQdkpRT.Anchor:SetPoint("BOTTOMLEFT", UIParent, "BOTTOMLEFT", x, y)
	else
		EQdkpRT.Anchor:SetPoint("TOPLEFT", UIParent, "BOTTOMLEFT", x, y)
	end
	self.db.profile.PositionX, self.db.profile.PositionY = x, y
end

function EQdkpRT:SetTitle(t)
	self.currentTitle = t and strlen(t) > 0 and t or self.defaultTitle
	-- self:SetTitleInternal()
	self.TitleText:SetText(self.currentTitle)
end

local lastUsageUpdate = 0
function EQdkpRT:SetTitleInternal()
	-- self.TitleText:SetText(("%s"):format(self.currentTitle, GetAddOnMemoryUsage("EQdkpRT")))
	if GetTime() - lastUsageUpdate > 8 then
		UpdateAddOnMemoryUsage()
		lastUsageUpdate = GetTime()
	end
-- geh	local a, b = Threat:TableStats()
-- geh	self.TitleText:SetText(("%s [%2.1fkb, %2.1fkb, %s/%s t used/alloc]"):format(self.currentTitle, GetAddOnMemoryUsage("EQdkpRT"), GetAddOnMemoryUsage("Threat-2.0"), a, b))
end

local frames = {"BarList", "Title", "ModuleList"}

function EQdkpRT:UpdateDisplay()
	self.Anchor:SetScale(EQdkpRT.Options["Skin.Scale"] / 100.0)

	for _, f in pairs(frames) do
		local frame = self[f]
		frame:SetAlpha(self.Options["Skin.".. f .. ".Opacity"] or self.Options["Skin.Frames.Opacity"])
		frame:SetBackdrop({
			bgFile = Media:Fetch("background", self.Options["Skin." .. f .. ".Background.Texture"] or self.Options["Skin.Frames.Background.Texture"]),
			edgeFile = Media:Fetch("border", self.Options["Skin." .. f .. ".Border.Texture"] or self.Options["Skin.Frames.Border.Texture"]),
			tile = true,
			tileSize = 16,
			edgeSize = 16,
			insets = {left = 4, right = 4, top = 4, bottom = 4}
		})
		local c = self.Options["Skin." .. f .. ".Background.Color"] or self.Options["Skin.Frames.Background.Color"]
		frame:SetBackdropColor(c.r, c.g, c.b, c.a)
		local c = self.Options["Skin." .. f .. ".Border.Color"] or self.Options["Skin.Frames.Border.Color"]
		frame:SetBackdropBorderColor(c.r, c.g, c.b, c.a)
	end

	local clamp = self.Options["Skin.Clamp"]
	self.BarList:SetClampedToScreen(clamp)

	-- Title
	if self.Options["Skin.Title.Hide"] then
		self.Title:Hide()
		self.Title:SetClampedToScreen(false)
	else
		self.Title:SetHeight(self.Options["Skin.Title.Height"])
		self.Title:SetClampedToScreen(clamp)
		if self.Options["Skin.Title.HideVersion"] then
			self.VersionText:Hide()
		else
			self.VersionText:Show()
		end
		local p, s, v = self.TitleText:GetFont()
		self.TitleText:SetFont(Media:Fetch("font", EQdkpRT.Options["Skin.Title.Font"]), s, v)
		self.Title:Show()
	end

	if self.Options["Skin.Modules.Hide"] then
		self.ModuleList:Hide()
		self.ModuleList:SetClampedToScreen(false)
	else
		self.ModuleList:Show()
		self.ModuleList:SetClampedToScreen(clamp)
	end

	self:UpdateBarLayouts()

	if self.Options["Lock"] then
		self.Grip:Hide()
	else
		self.Grip:Show()
	end

	return self.activeModule and self.activeModule:UpdateLayout()
end

function EQdkpRT:LayoutModuleIcons()
	local anchor, anchorPoint, offset = self.ModuleList, "LEFT", 6
	self.ModuleList:SetHeight(EQdkpRT.Options["Skin.Modules.Height"])
	for k, v in self:IterateModules() do
		local icon = module_icons[k]
		if not icon then
			icon = CreateFrame("Button", nil, self.ModuleList)
			module_icons[k] = icon
		end
		icon:SetWidth(self.ModuleList:GetHeight() - 12)
		icon:SetHeight(self.ModuleList:GetHeight() - 12)
		icon:SetNormalTexture(v.icon)
		icon:SetHighlightTexture("Interface\\Buttons\\ButtonHilight-Square")
		icon.module = v
		v.button = icon
		icon:SetScript("OnClick", function(self)
			self.module:Enable()
		end)
		icon:SetScript("OnEnter", function(self)
			GameTooltip:ClearLines();
			GameTooltip:SetOwner(self, "ANCHOR_RIGHT");
			GameTooltip:AddLine(self.module:Hint())
			GameTooltip:Show()
		end)
		icon:SetScript("OnLeave", function(self)
			GameTooltip:Hide()
		end)
		icon:GetNormalTexture():SetDesaturated(not v:IsEnabled())

		icon:ClearAllPoints()
		icon:SetPoint("LEFT", anchor, anchorPoint, offset, 0)
		anchor, anchorPoint, offset = icon, "RIGHT", 4
	end
	self.ModuleList.Config:SetWidth(self.ModuleList:GetHeight() - 12)
	self.ModuleList.Config:SetHeight(self.ModuleList:GetHeight() - 12)
end

function EQdkpRT:UpdateVisible()
	if self.Options["Standby"] then
		self.Anchor:Hide()
		return
	end
	local inInstance, kind = IsInInstance()
	local show
	if (not EQdkpRT.Options["ShowWith.Resting"] and IsResting()) then
		show = false
	end
	if (not EQdkpRT.Options["ShowWith.PVP"] and inInstance and (kind == "pvp" or kind == "arena")) then
		show = false
	end
	if show == nil then
		show =	(EQdkpRT.Options["ShowWith.Pet"] and UnitExists("pet")) or
				(EQdkpRT.Options["ShowWith.Alone"] and GetNumPartyMembers() + GetNumRaidMembers() == 0 and not UnitExists("pet")) or
				(EQdkpRT.Options["ShowWith.Party"] and GetNumPartyMembers() > 0) or
				(EQdkpRT.Options["ShowWith.Raid"] and GetNumRaidMembers() > 0)
	end
	if self.Options["ShowWith.Alone"] then
-- geh		Threat:RequestActiveOnSolo(true)
	end
	if show and not EQdkpRT.Options["HardOff"] then
		self.Anchor:Show()
	else
		self.Anchor:Hide()
	end
end

function EQdkpRT:SetOutOfDate(callback, minor, revision, sender, incompatible)
	self.OutOfDateText:SetFormattedText("|cffff0000new!|r r|cffffffff%s|r%s", revision, incompatible and " |cffff0000incompatible!|r" or "")
end
